<?
/**
 * VoiceOne Settings/Rules/incoming
 *
 * Frontend to provide access to the rules system in voiceone.
 * @package voiceone
 * @subpackage  settings_rules
 */
  include ("../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage,$relBasePath;
  $alert=getAlert();
  //================ POST & GET ================
  // delete ruleset
  if ($_GET["cmd"]=="del") {
    $ret=$asterisk->delRule($_GET["id"]);
    if ($ret==1) $alert="<div class=\"AlertGood\">".T_("Ruleset deleted")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Error: Ruleset not deleted")."</div>";
    goToMainPage($alert,"./");
  }
  // delete rule
  if ($_GET["cmd"]=="delrule") {
    $ret=$asterisk->delIncomingRule($_GET["id"]);
    if ($ret==1) $alert="<div class=\"AlertGood\">".T_("Incoming Rule deleted")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Error: Incoming rule not deleted")."</div>";
    goToMainPage($alert,"./");
  }
  // move rule up
  if ($_GET["cmd"]=="up") {
    $ret=$asterisk->moveRule($_GET["id"],1,RULE_INCOMING,0);
    if ($ret==1) $alert="<div class=\"AlertGood\">".T_("Incoming Rule Moved")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Error: Incoming rule not moved")."</div>";
    $scriptFade="<script>Fat.fade_element(\"row".$_GET["id"]."\", 30, 500, \"#FFFF33\", \"#FFFFFF\");</script>";
    goToMainPage($alert,"./?id=".$_GET["id"]);
  }
  // move rule down
  if ($_GET["cmd"]=="down") {
    $ret=$asterisk->moveRule($_GET["id"],-1,RULE_INCOMING,0);
    if ($ret==1) $alert="<div class=\"AlertGood\">".T_("Incoming Rule Moved")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Error: Incoming rule not moved")."</div>";
    $scriptFade="<script>Fat.fade_element(\"row".$_GET["id"]."\", 30, 500, \"#FFFF33\", \"#FFFFFF\");</script>";
    goToMainPage($alert,"./?id=".$_GET["id"]);
  }
  // move rule top
  if ($_GET["cmd"]=="top") {
    $ret=$asterisk->moveRule($_GET["id"],1,RULE_INCOMING,1);
    if ($ret==1) $alert="<div class=\"AlertGood\">".T_("Incoming Rule Moved")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Error: Incoming rule not moved")."</div>";
    $scriptFade="<script>Fat.fade_element(\"row".$_GET["id"]."\", 30, 500, \"#FFFF33\", \"#FFFFFF\");</script>";
    goToMainPage($alert,"./?id=".$_GET["id"]);
  }
  // move rule bottom
  if ($_GET["cmd"]=="bottom") {
    $ret=$asterisk->moveRule($_GET["id"],-1,RULE_INCOMING,1);
    if ($ret==1) $alert="<div class=\"AlertGood\">".T_("Incoming Rule Moved")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Error: Incoming rule not moved")."</div>";
    $scriptFade="<script>Fat.fade_element(\"row".$_GET["id"]."\", 30, 500, \"#FFFF33\", \"#FFFFFF\");</script>";
    goToMainPage($alert,"./?id=".$_GET["id"]);
  }
  // delete ruleset
  if ($_GET["cmd"]=="deljump") {
    //get ruleset
    $ret=$asterisk->getRule($_GET["id"],0);
    if((!is_array($ret))||(!is_array($ret[0]))){
      $ret=0;
    }else{
      $entry=Array(
        "id" => $ret[0]["id"],
        "name" => $ret[0]["name"],
        "description" => $ret[0]["description"],
        "type" => RULE_INCOMING, 
        "jump" => ""
      );
      $ret=$asterisk->putRule($entry);
    }
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("Ruleset jump has been removed")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Error: Ruleset jump not removed")."</div>";
    goToMainPage($alert,"./");
  }
  // set flash
  if((isset($_GET["id"]))&&($_GET["id"]!=0)){
    $scriptFade="<script>Fat.fade_element(\"row".$_GET["id"]."\", 30, 500, \"#FFFF33\", \"#FFFFFF\");</script>";
  }
  //================ PAGE LOGIC ================
  //get the rules
  $ret=$asterisk->getRule(0,RULE_INCOMING);
  if($err=$asterisk->getError()) die("Error: $err");
  if(is_array($ret)){
    foreach($ret as $v){
      $id=$v["id"];
      $name=$v["name"];
      $description=$v["description"];
      $incoming=$v["incoming"];
      $jump=$v["jump"];
      $add="<a class=\"admin\" href=\"edit-rule/?rule=$id\">(<!--<img src=\"$relBasePath/public/img/icon_add.gif\" alt=\"Add a new rule\" />-->".T_("Add a new Rule").")</a> ";
      $delete="<a class=\"admin\" href=\"$PHP_SELF?cmd=del&id=$id\" onclick=\"if (confirm('".sprintf(T_("Are you sure to delete ruleset %s"),$name)." ?')) return true; else return false;\"><img src=\"$relBasePath/public/img/trash.gif\" /></a> ";
      $html.="<div class=\"ruleTitle\"><strong>".T_("Rule set n&deg; ")."$id: <a href=\"edit/?id=$id\">$name</a></strong> $add $delete</div>\n";
      if ($description!="") $html.="<div class=\"ruleTitle\"><p>$description</p></div>\n";
      $html.="<table class=\"todolist\" cellspacing=0>";
      $html.="<tr>";
      $html.="<th colspan=\"6\">&nbsp;</th><th>".T_("N&deg;")."</th>";
      $html.="<th >".T_("Time Segment")."</th>";
      $html.="<th class=\"green\">".T_("Caller Id")."</th>";
      $html.="<th >".T_("Line")."</th>";
      $html.="<th >".T_("Number")."</th>";
      $html.="<th >".T_("Macro")."</th>";
      $html.="<th >".T_("Params")."</th>";
      //$html.="<th>&nbsp;</th>";
      $html.="</tr>";
      $count=1;
      //Verify jump
      if((is_array($jump))&&($jump["ruleset_to"]!=0)){
        ob_start();
        ?>
        <tr class="firstofgroup rule" id="row0">
          <td colspan="13" class="jump" style="background:#C00;text-align:center;">
            <div style="float:left;vertical-align:top;text-align:right;line-height:20px;padding:5px 20px;">
              <img style="vertical-align:bottom;" src="<?=$relBasePath?>/public/img/warning.png" alt="Warning">
              <strong style="font-size:12px;color:yellow;"><?=T_("JUMP SET")?>:</strong>
            </div>
            <div style="float:left;vertical-align:top;text-align:left;padding:5px 0;">
              <span style="color:yellow;">
                <?=sprintf(T_("All calls sent to this ruleset are forwarded to rule set n.%s"),$jump["ruleset_to"])?><br/>
                <?=sprintf(T_("Jump will expire at %s"),$jump["end_of_life"])?>
              </span>
            </div>
            <button style="margin-left:15px;font-size:12px;cursor:pointer;margin:5px 0;" onclick="location.href='<?=$PHP_SELF?>?cmd=deljump&id=<?=$id?>'"><?=T_("Remove Jump")?></button>
          </td>
        </tr>
        <?
        $html.=ob_get_contents();
        ob_end_clean();
      }
      //Print rules
      if(is_array($incoming)){
        foreach($incoming as $i){
          $ruleDisabled=false;
          $idr=$i["id"];
          $priority=$i["priority"];
          $duration=intval($i["duration"]);
          //Extract TIMESEGMENT
          if ($i["timesegment"]=="0") $timesegment="*";
          else {
            $timesegment=$asterisk->getTimeSegment($i["timesegment"]);
            if((is_array($timesegment))&&(is_array($timesegment[0]))&&($timesegment[0]["name"]!="")) $timesegment=$timesegment[0]["name"];
            else {
              $timesegment=T_("deleted timesegment");
              $ruleDisabled=true;
            }
          }
          //Extract CALLER ID
          switch ($i["callertype"]) {
            case CALLER_ALL:
              $callerid="*";
            break;
            case CALLER_ANONYMOUS:
              $callerid=T_("Anonymous");
            break;
            case CALLER_ID:
              $callerid=$i["callerid"];
            break;
            case CALLER_CLASS:
              $icon_group="<div style=\"float: left; margin-right: 2px;\"><img src=\"$relBasePath/public/img/icon_number.gif\" alt=\"class of phonenumbers\" /></div>";
              $numberclass=$asterisk->getPhoneNumber($i["callerid"]);
              if((is_array($numberclass))&&(is_array($numberclass[0]))&&($numberclass[0]["name"]!="")){
                $callerid=$icon_group."<span>".$numberclass[0]["name"]."</span>";
              }else{
                $callerid=$icon_group."<span>".T_("deleted Caller Id")."</span>";
                $ruleDisabled=true;
              }
            break;
            case CALLER_GROUP:
              $icon_group="<div style=\"float: left; margin-right: 2px;\"><img src=\"$relBasePath/public/img/icon_numbers.gif\" alt=\"group of phonenumbers\" /></div>";
              $group=$asterisk->getGroup($i["callerid"],GROUP_OF_PHONENUMBER);
              if((is_array($group))&&(is_array($group[0]))&&($group[0]["name"]!="")){
                if($group[0]["metagroup"]) $grpname="<strong>[".strtoupper(str_replace("-"," ",str_replace("_","",$group[0]["name"])))."]</strong>";
                else $grpname="[".str_replace("-"," ",str_replace("_","",$group[0]["name"]))."]";
                $callerid=$icon_group."<span>".$grpname."</span>";
              }else{
                $callerid=$icon_group."<span>".T_("deleted Caller Id")."</span>";
                $ruleDisabled=true;
              }
            break;
            default:
              error_log("ERROR: unknown callertype in incoming rule");
              $ruleDisabled=true;
            break;
          }
          //Extract TRUNK
          if ($i["from_channel"]!="" and $i["from_channel"]!=0) {
            $t=$asterisk->getTrunk($i["from_channel"],0);
            if((is_array($t))&&(is_array($t[0]))&&($t[0]["name"]!="")){
              $trunk=$t[0]["name"];
            }else{
              $trunk=T_("deleted line");
              $ruleDisabled=true;
            }
          } else $trunk="*";
          //Extract PHONE NUMBERS
          if (count($i["from_number"])==0 or $i["from_number"]=="" or in_array("",$i["from_number"]) ) $number="*";
          else if(count($i["from_number"])<6) $number=implode("<br/>",$i["from_number"]);
          else {
            $maxNumberLength=0;
            $numberTable="";
            foreach($i["from_number"] as $n){
              $numberTable.=$n."<br/>";
              if(strlen($n)>$maxNumberLength) $maxNumberLength=(strlen($n)+2);
            }
            $number="<div style=\"overflow-y: scroll; overflow-x: hidden; width: ".$maxNumberLength."em; height: 6em; padding: 0px; margin: 5px auto 5px auto; \"> ".$numberTable."</div>";
          }
          //Extract MACRO (name and parameters)
          $parameter="";
          $m=$asterisk->getMacro($i["macro"]);
          if((is_array($m))&&(is_array($m[0]))&&($m[0]["label"]!="")){
            $macro=$m[0]["label"];
            $parameterList=$i["parameter"];
            if($parameterList==""){
              $parameter=T_("[none]");
            }else{
              $k=0;
              $parameter="";
              $parameterList=split("\|",$parameterList);
              $parameterValue=$asterisk->resolveMacroParam($i["macro"],$i["parameter"]);
              $parameterValue=split("\|",substr($parameterValue,1));
              foreach($parameterList as $param){
                list($label)=split("=",$param);
                $value=$parameterValue[$k];
                $value=str_replace("\"","",$value);
                if(strlen($value)>13) $valueTr=substr($value,0,10)."...";
                else $valueTr=$value;
                $parameter.="<a title=\"$value\">$label</a>=".$valueTr."<br/>";
                $k++;
              }
            }
          }else{
            $macro=T_("deleted macro");
            $parameter=T_("[none]");
            $ruleDisabled=true;
          }
          // Define BUTTONS
          $button="";
          if ($count==1) $button.="<td class=\"rulebutton\">&nbsp;</td><td class=\"rulebutton\">&nbsp;</td>";
          else $button.="<td class=\"rulebutton\"><a href=\"?cmd=top&id=$idr\"><img src=\"$relBasePath/public/img/icon_top.gif\" alt=\"top\" /></a></td><td class=\"rulebutton\"><a href=\"?cmd=up&id=$idr\"><img src=\"$relBasePath/public/img/icon_up.gif\" alt=\"up\" /></a></td>";
          if ($count==count($incoming)) $button.="<td class=\"rulebutton\">&nbsp;</td><td class=\"rulebutton\">&nbsp;</td>";
          else $button.="<td class=\"rulebutton\"><a href=\"?cmd=down&id=$idr\"><img src=\"$relBasePath/public/img/icon_down.gif\" alt=\"down\" /></a></td><td class=\"rulebutton\"><a href=\"?cmd=bottom&id=$idr\"><img src=\"$relBasePath/public/img/icon_bottom.gif\" alt=\"bottom\" /></a></td>";
          if ($duration=="0") $stop="<img src=\"$relBasePath/public/img/stop.gif\" alt=\"stop executing after this rule\" />";
          else $stop="<img src=\"$relBasePath/public/img/continue.gif\" alt=\"continue executing after this rule\" />";
          $button.="<td class=\"rulebutton\"><a href=\"edit-rule/?rule=$id&id=$idr\"><img src=\"$relBasePath/public/img/icon_edit.gif\" alt=\"edit\" /></a></td>";
          $button.="<td class=\"rulebutton\"><a href=\"?cmd=delrule&id=$idr\" onclick=\"if (confirm('".sprintf(T_("Are you sure to delete rule %s"),$idr)." ?')) return true; else return false;\"><img src=\"$relBasePath/public/img/icon_remove.gif\" alt=\"remove\"/></a></td>";
          // Build TABLE'S ROW
          if($ruleDisabled===true){
            ob_start();
            ?>
            <tr class="firstofgroup rule" id="row<?=$idr?>">
              <?=$button?>
              <td class="disabled"><b><?=$idr?></b></td>
              <td class="disabled"><?=$timesegment?></td>
              <td class="disabled"><?=$callerid?></td>
              <td class="disabled"><?=$trunk?></td>
              <td class="disabled"><?=$number?></td>
              <td class="disabled"><?=$macro?></td>
              <td class="disabled"><?=$parameter?></td>
              <!--td class="disabled"><?=$stop?></td-->
            </tr>
            <?
            $html.=ob_get_contents();
            ob_end_clean();
          }else{
            ob_start();
            ?>
            <tr class="firstofgroup rule" id="row<?=$idr?>">
              <?=$button?>
              <td class="green"><b><?=$idr?></b></td>
              <td><?=$timesegment?></td>
              <td class="green"><?=$callerid?></td>
              <td><?=$trunk?></td>
              <td ><?=$number?></td>
              <td class="highlight"><?=$macro?></td>
              <td><?=$parameter?></td>
              <!--td><?=$stop?></td-->
            </tr>
            <?
            $html.=ob_get_contents();
            ob_end_clean();
          }
          $count++;
        }
      }
      $html.="</table><br/>\n";
    }
  }
  //================ MAIN CONTENTS ================
  ob_start();
  ?>
  <?$sel="incoming";include("../navigation.php");?>

  <div class="SectionHeader">
    <?=$alert?>
    <h1><?=T_("Incoming calls Rules")?></h1>
    <h3><a href="edit/" class="admin" ><?=T_("New incoming rule set")?></a></h3>
  </div>
  <div id="basic_form">
    <?=$html?>
  </div>
  <?
  echo $scriptFade;
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start();
  ?>
        <div class="Sidebar">
          <h1><?=T_("Incoming Rule")?></h1>
          <p><?=T_("This rules will be applied on incoming calls")?></p>
        </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
  $smarty->assign("section", "rules");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>

